package com.symbio.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

@WebServlet("/checkCode")
public class CheckCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int width = 100;
        int height = 50;
        /* 创建图片对象 */
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        /*填充背景色*/
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.pink);
        graphics.fillRect(0, 0, width, height);

        /*画边框*/
        graphics.setColor(Color.blue);
        graphics.drawRect(0, 0, width - 1, height - 1);

        /*获取所有字符*/
        ArrayList<String> arrayList = new ArrayList();
        for (int i = 0; i < 26; i++) {
            arrayList.add(String.valueOf((char)(65+i)));
            arrayList.add(String.valueOf((char)(97+i)));
            if (i < 10) {
                arrayList.add(String.valueOf(i));
            }
        }

        /*生成随机码*/
        Random random = new Random();

        String code = "";
        for (int i = 0; i < 4; i++) {
            String s = arrayList.get(random.nextInt(arrayList.size()));
            code += s;
            graphics.drawString(s, width/5*i + width/10, height/2);
        }

        request.getSession().setAttribute("checkCode_session", code);
        /*绘制干扰线*/
        for (int i = 0; i < 5; i++) {
            graphics.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
        }

        /*图片输入到页面*/
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
